const express = require("express");
const app = express();
const ip = require("ip");
const IP = ip.address();
const port = 3000;
const expressJWT = require("express-jwt");
const path = require("path");
const userRouter = require("./router/users/user.js");
const userDetails = require("./router/users/userInfo");
const uploadAvatar = require("./router/upload/avatar");
const uploadGoods = require("./router/upload/goods");
const goods = require("./router/goods/list_info.js");
const cors = require("cors");
const { verToken } = require("./utils/token");
const signkey = "jwt"; // 秘钥
app.use(express.static(path.join(__dirname, "public")));
// 允许跨域
app.use(cors());

// 服务端校验token

app.use((req, res, next) => {
  let token = req.headers.authorization;
  if (token) {
    const flag = verToken(token);
    if (!flag) {
      res
        .send({
          status: "fail",
        })
        .status(500);
    }
  }
  next();
});

app.use(
  expressJWT({
    secret: signkey,
    algorithms: ["HS256"],
  }).unless({
    // 以下路径携带token
    path: [
      "/users/login",
      "/users/register",
      "/info/update/forgetPwd",
      "/upload/avatar",
      "/upload/goods",
      "/upload/goodsList",
    ],
  })
);
// 捕获错误的全局中间件
app.use((err, req, res, next) => {
  // token过期
  if (err.status == 401) {
    res.status(401).send({
      status: "fail",
      message: err.message,
    });
    return;
  }
  if (err) {
    res.status(500).send({
      status: "fail",
      message:"系统内部错误,请稍后再访问"
    });
  }
});

// 用户相关
app.use("/users", userRouter);
// 用户详情信息
app.use("/info", userDetails);
// 商品相关
app.use("/goods", goods);

// 上传头像图片
app.use("/upload/avatar", uploadAvatar);
// 上传商品图片
app.use("/upload", uploadGoods);

app.listen(port, () => {
  console.log(`http://${IP}:${port}, 启动成功啦`);
});
